import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//引入element-plus
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//引入图标组件
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from "axios";
//引入修改elementPlus的默认为中文的依赖
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

const BASE_URL = 'http://localhost:8080';
window.BASE_URL = BASE_URL;
//创建vue实例
const app = createApp(App)

app.config.globalProperties.BASE_URL = BASE_URL;
//开启跨域携带cookie
window.axios=axios;
axios.defaults.withCredentials = true;
//替换全局axios
app.config.globalProperties.$axios = axios;
//axios响应拦截器，处理射出的响应状态码
axios.interceptors.response.use(
    response =>response,
    error =>{
        //控制台打印异常
        console.log(error);
        //提示客户有异常
        ElMessage.error(error.response.data.msg);
        if(error.response.status == 401 || error.response.response.status == 403){
            //将localStorage中的用户以及面包屑移除
            localStorage.removeItem("user");
            localStorage.removeItem("breadcrumb");
            //重新加载
            window.location.reload();
        }else if(error.response.data.path.indexOf("login")!=-1 && error.response.status ==404){
            //重新加载
            window.location.reload();
        }
    }
)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(ElementPlus,{locale:zhCn}).use(store).use(router).mount('#app')

window.getUser = () =>{
    return localStorage.user?JSON.parse(localStorage.user):null;
}
//8.解决ResizeObserver Error
//防抖函数 它接受一个函数 fn 和一个延迟时间 delay
//通过包装 ResizeObserver 的回调函数到一个防抖（debounce）函数中，
//你减少了回调函数的执行频率，从而可能提高了应用的性能
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
//覆盖
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}